package com.cicc.wm;


import com.cicc.wm.lock.DistributedLock;
import com.cicc.wm.lock.LockRegistryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 锁服务测试
 */
@Slf4j
@RestController
public class WmController {

    @GetMapping("/lock")
    public String lock(@RequestParam("lockKey") String lockKey) throws InterruptedException {
        DistributedLock distributedLock = LockRegistryFactory.getLockRegistry().obtain(lockKey);
        try {
            distributedLock.lock();
            log.info("lock获取锁成功");
            TimeUnit.SECONDS.sleep(60);
        } finally {
            distributedLock.unlock();
        }
        return "lock业务执行完毕";
    }

    @GetMapping("/lock/lease")
    public String lockLease(@RequestParam("lockKey") String lockKey, @RequestParam("leaseTime") int leaseTime) throws InterruptedException {
        DistributedLock distributedLock = LockRegistryFactory.getLockRegistry().obtain(lockKey);
        try {
            distributedLock.lock(leaseTime, TimeUnit.SECONDS);
            log.info("lock/lease获取锁成功");
            TimeUnit.SECONDS.sleep(40);
        } finally {
            distributedLock.unlock();
        }
        return "lockLease业务执行完毕";
    }

    @GetMapping("/tryLock")
    public String tryLock(@RequestParam("lockKey") String lockKey) throws InterruptedException {
        DistributedLock distributedLock = LockRegistryFactory.getLockRegistry().obtain(lockKey);
        try {
            boolean isLocked = distributedLock.tryLock(5, TimeUnit.SECONDS);
            if (isLocked) {
                log.info("tryLock获取锁成功");
                TimeUnit.SECONDS.sleep(60);
            } else {
                return "tryLock获取锁失败";
            }
        } finally {
            distributedLock.unlock();
        }
        return "tryLock业务执行完毕";
    }

    @GetMapping("/tryLock/lease")
    public String tryLockLease(@RequestParam("lockKey") String lockKey, @RequestParam("leaseTime") int leaseTime) throws InterruptedException {
        DistributedLock distributedLock = LockRegistryFactory.getLockRegistry().obtain(lockKey);
        try {
            boolean isLocked = distributedLock.tryLock(5, leaseTime, TimeUnit.SECONDS);
            if (isLocked) {
                log.info("tryLockLease获取锁成功");
                TimeUnit.SECONDS.sleep(60);
            } else {
                return "tryLockLease获取锁失败";
            }
        } finally {
            distributedLock.unlock();
        }
        return "tryLockLease业务执行完毕";
    }
}
